
import React, { useState, useEffect, useRef } from "react";
import Common from "@/components/common/index"
import { Button, Form, Input, Table, Pagination, Upload, Typography, Popconfirm, Modal } from 'antd';
import { SearchOutlined, ReloadOutlined, CloudUploadOutlined } from '@ant-design/icons';
import type { TableColumnsType, PaginationProps, UploadProps } from 'antd';
import { placeSort, updatePri } from "@/common/api"
import Detail from "./detail";



const Base: React.FC = () => {
    useEffect(() => {
        getData()
    }, []);
    const [form2] = Form.useForm();
    const [loadings, setLoadings] = useState<boolean>(false);
    const [tableData, setTableData] = useState<any[]>([]);
    const onFinish = () => {
        pageNumRef.current = 1;
        setCurrent(1)
        getData()
    };

    const props: UploadProps = {
        name: 'file',
        showUploadList: false,
        action: () => {
            if (process.env.NODE_ENV == "development") {
                return `http://192.168.10.87:8611/api/placeDistance/import?fileName=${formData.fileName}&priority=${formData.priority}`;
            } else {
                const host = window.location.protocol + "//" + window.location.host;
                return `${host}/api/placeDistance/import?fileName=${formData.fileName}&priority=${formData.priority}`;
            }
        },
        headers: {},
        onChange(info) {
            if (info.file.status !== 'uploading') {
            }
            if (info.file.status === 'done') {
                if (info.file.response.success) {
                    $message.success(info.file.response.message);
                    form3.resetFields();
                    setVisible(false)
                    getData()
                } else {
                    $message.error(info.file.response.message);
                }
            } else if (info.file.status === 'error') {
                $message.error('导入失败');
            }
        },
    };
    const uploadRef = useRef<HTMLButtonElement>(null);
    const getTop = () => {
        return <Form
            layout="inline"
            form={form2}
            onFinish={onFinish}
            autoComplete="off"
        >

            <Form.Item name="fileName" label="配送区域里程表:">
                <Input placeholder="请输入配送站点" />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<SearchOutlined />} type="primary" htmlType="submit" loading={loadings}>查询</Button>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<ReloadOutlined />} onClick={() => {
                    form.resetFields();
                }} loading={loadings}>重置</Button>
            </Form.Item>



            <Form.Item style={{ marginBottom: '10px' }}>
                <Upload {...props} style={{ display: 'none' }} >
                    <Button icon={<CloudUploadOutlined />} type="primary" ref={uploadRef}>导入</Button>
                </Upload>
                <Button icon={<CloudUploadOutlined />} type="primary" onClick={() => setVisible(true)}>导入</Button>
            </Form.Item>


        </Form>
    }


    const getData = () => {
        const values = form.getFieldsValue();
        let param = {
            ...values,
            pageSize: pageSizeRef.current,
            pageNum: pageNumRef.current
        }
        setLoadings(true)
        placeSort(param).then((res: any) => {
            setLoadings(false)
            if (res.success) {
                setTableData(res.data.records)
                total.current = res.data.total
            } else {

            }
        })
    }
    const [form] = Form.useForm();
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record: any) => record.id === editingKey;
    const getCell = (record: any, title: any, dataIndex: any) => {
        return {
            record,
            dataIndex: dataIndex,
            title: title,
            inputType: 'text',
            editing: isEditing(record),
        }
    }
    const edit = (record: any) => {
        form.setFieldsValue(record)
        setEditingKey(record.id);
    }
    const cancel = () => {   //取消编辑
        setEditingKey('');
    };
    const save = async (record: any) => {
        try {
            const row = await form.validateFields();
            updatePri({ id: record.id, ...row }).then((res: any) => {
                if (res.success) {
                    $message.success('修改成功');
                    setEditingKey('');
                    getData()
                } else {
                    $message.error(res.message);
                }
            })

        } catch (errInfo) {
            console.log('验证失败:', errInfo);
        }
    }
    const columns: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 60,
            align: 'center' as const,
            render: (_text, _record, index) =>
                (pageNumRef.current - 1) * pageSizeRef.current + index + 1,
        },

        {
            title: '配送里程表名称',
            dataIndex: 'fileName',
            // width: 100,
        },
        {
            title: '优先级',
            dataIndex: 'priority',
            width: 150,
            onCell: (record) => (getCell(record, '优先级', 'priority'))

        },
        {
            title: '配送站点数(个)',
            dataIndex: 'placeNum',
            width: 200,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            render: (_: any, record) => {
                const editable = isEditing(record);

                return editable ? (
                    <span>
                        <Typography.Link style={{ marginInlineEnd: 8 }} onClick={() => cancel()}>
                            取消
                        </Typography.Link>
                        <Popconfirm title="是否确认?" onConfirm={() => save(record)}>
                            <a>确认</a>
                        </Popconfirm>
                    </span>
                ) : (
                    <>
                        <Typography.Link onClick={() => edit(record)} style={{ marginRight: 16 }}>
                            编辑
                        </Typography.Link>
                        <Typography.Link onClick={() => detail(record)} >
                            详情
                        </Typography.Link>

                    </>
                );
                // <>
                //     <Typography.Link onClick={() => detail(record)} >
                //         详情
                //     </Typography.Link>
                // </>

            },
        },



    ];
    const [data, setData] = useState(null);
    const detail = (record: any) => {
        setData({ ...record })  //创建一个新的对象,改变内存地址，触发子组件useEffect
    }
    interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
        editing: boolean;
        dataIndex: string;
        title: any;
        inputType: 'number' | 'text';
        record: any;
        index: number;
    }
    const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }) => {
        const inputNode = <Input />;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{ margin: 0 }}
                        rules={[
                            {
                                required: false,
                                message: `请输入 ${title}!`,
                            },
                        ]}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };

    const getTable = () => {
        return <Form form={form} component={false}> <Table
            components={{
                body: { cell: EditableCell },
            }}
            columns={columns}
            dataSource={tableData}
            scroll={{ x: 'max-content' }}
            pagination={false}
            sticky={true}
            style={{ height: '90%', overflowY: 'auto', overflowX: 'hidden' }}
            rowKey="id"
        /></Form >
    }
    const total = useRef(0);
    const pageNumRef = useRef(1);
    const pageSizeRef = useRef(10);
    const [current, setCurrent] = useState<number>(1);
    const onChange: PaginationProps['onChange'] = (page, pageSize) => {
        pageNumRef.current = page;
        pageSizeRef.current = pageSize;
        setCurrent(page)
        getData()
    }
    const getPagination = () => {
        return <> <Pagination
            size="small"
            total={total.current}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={onChange}
            current={current}
        />
            <Detail data={data} />
            {getModal()}
        </>

    }

    const [visible, setVisible] = useState<boolean>(false);
    const [form3] = Form.useForm();
    const [formData, setFormData] = useState({ priority: '', fileName: '' });
    const closeM = () => {
        setVisible(false)
    }
    const handleOk = async () => {
        try {
            // 触发表单校验
            const values = await form3.validateFields();
            const { priority, fileName } = values
            setFormData({ priority, fileName })
            uploadRef.current?.click();
        } catch (error) {
            console.error('表单校验失败:', error);
        }
    };
    const getModal = () => {
        return <>
            <Modal
                title='提示'
                open={visible}
                onCancel={closeM}
                width="40vw"
                footer={[
                    <Button key="back" onClick={() => setVisible(false)} style={{ marginRight: '10px' }}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" onClick={handleOk}>
                        确认
                    </Button>
                ]}
            >
                <Form form={form3} autoComplete="off" labelAlign="right" labelCol={{ style: { width: 150, textAlign: 'right' } }} >
                    <Form.Item name="fileName" label="配送里程表名称:" rules={[{ required: true, message: '请输入配送里程表名称' }]} >
                        <Input placeholder="请输入配送里程表名称" />
                    </Form.Item>
                    <Form.Item name="priority" label="优先级:">
                        <Input placeholder="请输入优先级" />
                    </Form.Item>
                </Form>
            </Modal>

        </>
    }


    return <>
        <Common top={getTop()} table={getTable()} paginations={getPagination()} />
    </>
}

export default Base